const glob = require('glob');
const path = require('path');
const fs = require('fs');

module.exports = async function (fastify, options) {
  const controllers = glob.sync("**.js", {matchBase: true, cwd: process.cwd() + '/controller/'});
  for (const controller of controllers) {
    const Ctrl = require(path.resolve(process.cwd() + '/controller/', controller));

    if (!(new Ctrl() instanceof saas.controller)) {
      continue;
    }

    const paths = path.parse(controller);
    if (!saas.isEmpty(paths.dir))
      paths.dir = '/' + paths.dir;
    paths.name = '/' + paths.name;

    const methods = Object.getOwnPropertyNames(Ctrl.prototype);

    for (const method of methods) {

      let requestMethod;
      if (method.toLowerCase().endsWith('action') || method.toLowerCase().endsWith('actiondynamic')) {
        requestMethod = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTIONS']
      } else if (method.toLowerCase().endsWith('actionget')) {
        requestMethod = ['GET']
      } else if (method.toLowerCase().endsWith('actionpost')) {
        requestMethod = ['POST']
      } else {
        continue;
      }

      let actionName;
      if (method.toLowerCase().endsWith('actiondynamic')) {
        if (method.indexOf('_') > -1) {
          const actions = method.split('_');
          let params = [];
          for (let i = 0; i < actions.length; i++) {
            if (i !== actions.length - 1) {
              params.push(`:${actions[i]}`);
            } else {
              params.push(actions[i].replace(/actiondynamic/i, ''));
            }
          }
          actionName = params.join('/');
        } else {
          actionName = method.replace(/actiondynamic/i, '');
        }
      } else {
        actionName = method.replace(/actionget/i, '').replace(/actionpost/i, '').replace(/action/i, '');
      }
      
      // 加载验证器
      let schema = null;
      if (fs.existsSync(path.resolve(process.cwd() + '/schema/', controller))) {
        const schemaInstance = require(path.resolve(process.cwd() + '/schema/', controller));
        if(Object.getOwnPropertyNames(schemaInstance).some(p=>p === actionName)){
          schema = schemaInstance[actionName];
        }
      }

      // console.log(`register route: ${paths.dir}${paths.name}/${actionName} method:${requestMethod}`);
      fastify.route({
        method: requestMethod,
        url: `${paths.dir}${paths.name}/${actionName}`,
        handler: async function (request, reply) {
          const ct = new Ctrl(request, reply);
          if (ct['_before']) await ct['_before']();
          if (!reply.sent) await ct[method]();
          if (ct['_after']) await ct['_after']();
        },
        schema: schema
      })


    }
  }
  console.log('[saas-js-router] router loaded!');
};
